<template>
  <div class="masterdata-manage flex h-full">
    <!-- 左侧分类树区域 -->
    <div class="tree-container w-72 bg-white shadow-sm border-r border-gray-100 overflow-auto">
      <div class="p-4">
        <el-input 
          v-model="treeFilterText" 
          placeholder="按名称查询" 
          prefix-icon="i-carbon-search"
          clearable
          class="mb-3"
        />
      </div>
      
      <el-tree
        ref="categoryTreeRef"
        :data="categoryTree"
        :props="{ label: 'name', children: 'children' }"
        node-key="id"
        :filter-node-method="filterNode"
        highlight-current
        @node-click="handleNodeClick"
        class="custom-tree"
      >
        <template #default="{ node, data }">
          <div class="flex items-center">
            <div :class="getNodeIconClass(data)" class="mr-2 text-blue-500"></div>
            <span>{{ node.label }}</span>
            <span v-if="data.count" class="ml-2 px-2 py-0.5 text-xs bg-blue-50 text-blue-500 rounded-full">{{ data.count }}</span>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 右侧内容区域 -->
    <div class="content-container flex-1 overflow-auto bg-gray-50">
      <!-- 当显示总览时 -->
      <template v-if="currentView === 'overview'">
        <el-card shadow="hover" class="m-4">
          <template #header>
            <div class="flex justify-between items-center">
              <h2 class="text-xl font-bold">主数据总体情况</h2>
              <div>
                <el-button type="primary" @click="refreshData">
                  <div class="i-carbon-renew mr-1"></div>刷新
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="overview-stats grid grid-cols-4 gap-4 mb-6">
            <el-card shadow="hover" class="stat-card hover:translate-y-[-3px] transition-all duration-300">
              <div class="flex items-center">
                <div class="i-carbon-data-base text-5xl text-blue-500 mr-4"></div>
                <div>
                  <div class="text-3xl font-bold">{{ totalStats.entities }}</div>
                  <div class="text-gray-500">实体总数</div>
                </div>
              </div>
            </el-card>
            
            <el-card shadow="hover" class="stat-card hover:translate-y-[-3px] transition-all duration-300">
              <div class="flex items-center">
                <div class="i-carbon-document text-5xl text-green-500 mr-4"></div>
                <div>
                  <div class="text-3xl font-bold">{{ totalStats.records }}</div>
                  <div class="text-gray-500">数据记录数</div>
                </div>
              </div>
            </el-card>
            
            <el-card shadow="hover" class="stat-card hover:translate-y-[-3px] transition-all duration-300">
              <div class="flex items-center">
                <div class="i-carbon-folder text-5xl text-orange-500 mr-4"></div>
                <div>
                  <div class="text-3xl font-bold">{{ totalStats.categories }}</div>
                  <div class="text-gray-500">数据分类数</div>
                </div>
              </div>
            </el-card>
            
            <el-card shadow="hover" class="stat-card hover:translate-y-[-3px] transition-all duration-300">
              <div class="flex items-center">
                <div class="i-carbon-chart-column text-5xl text-purple-500 mr-4"></div>
                <div>
                  <div class="text-3xl font-bold">{{ totalStats.attributes }}</div>
                  <div class="text-gray-500">属性总数</div>
                </div>
              </div>
            </el-card>
          </div>
          
          <el-table
            :data="overviewTableData"
            style="width: 100%"
            border
            stripe
            row-key="id"
          >
            <el-table-column type="index" label="序号" width="80" align="center" />
            <el-table-column prop="entityCnName" label="表中文名称" min-width="180" />
            <el-table-column prop="tableName" label="表名" min-width="180" />
            <el-table-column prop="recordCount" label="数据记录数" width="120" align="center" />
            <el-table-column prop="fieldCount" label="字段数" width="80" align="center" />
          </el-table>
          
          <div class="pagination-container flex justify-end mt-4">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </template>
      
      <!-- 当显示实体数据表时 -->
      <template v-else-if="currentView === 'entityData'">
        <el-card shadow="hover" class="m-4">
          <template #header>
            <div class="flex justify-between items-center">
              <div class="flex items-center">
                <h2 class="text-xl font-bold">{{ currentEntity.name }}</h2>
                <el-tag type="info" class="ml-2">{{ currentEntity.code }}</el-tag>
              </div>
              <div class="flex space-x-2">
                <el-button type="primary" @click="showAdvancedSearch">
                  <div class="i-carbon-search mr-1"></div>高级查询
                </el-button>
                <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
                  <div class="i-carbon-trash-can mr-1"></div>删除
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 高级查询条件展示区域 -->
          <div v-if="searchConditions.length" class="search-conditions bg-blue-50 p-3 rounded-md mb-4">
            <div class="flex items-center justify-between mb-2">
              <div class="font-bold text-blue-600">
                <div class="i-carbon-filter mr-1 text-sm"></div>高级查询条件
              </div>
              <el-button type="primary" link @click="clearSearchConditions">
                <div class="i-carbon-close mr-1"></div>清除条件
              </el-button>
            </div>
            <el-tag 
              v-for="(condition, index) in searchConditions" 
              :key="index"
              class="mr-2 mb-1"
              closable
              @close="removeSearchCondition(index)"
            >
              {{ condition.fieldName }}: {{ condition.operator }} {{ condition.value }}
            </el-tag>
          </div>
          
          <!-- 实体数据表格 -->
          <el-table
            v-loading="tableLoading"
            :data="entityDataList"
            style="width: 100%"
            border
            stripe
            row-key="id"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column 
              v-for="column in entityColumns" 
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :min-width="column.minWidth"
            />
          </el-table>
          
          <div class="pagination-container flex justify-end mt-4">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </template>
    </div>
    
    <!-- 高级查询对话框 -->
    <el-dialog
      v-model="advancedSearchVisible"
      title="高级查询"
      width="800px"
      destroy-on-close
    >
      <div class="mb-4 flex justify-between items-center">
        <div class="text-gray-500">请添加查询条件</div>
        <el-button type="primary" @click="addSearchCondition">
          <div class="i-carbon-add mr-1"></div>添加
        </el-button>
      </div>
      
      <el-table
        :data="searchConditions"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="fieldName" label="字段名称" min-width="120" />
        <el-table-column prop="operator" label="逻辑运算" width="120" />
        <el-table-column prop="value" label="输入值" min-width="150" />
        <el-table-column prop="relation" label="条件关系" width="100" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" text size="small" @click="editSearchCondition(scope.row, scope.$index)">
              <div class="i-carbon-edit"></div>
            </el-button>
            <el-button type="danger" text size="small" @click="removeSearchCondition(scope.$index)">
              <div class="i-carbon-trash-can"></div>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="advancedSearchVisible = false">取消</el-button>
          <el-button type="primary" @click="executeAdvancedSearch">执行查询</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 添加/编辑查询条件对话框 -->
    <el-dialog
      v-model="conditionFormVisible"
      :title="isEditingCondition ? '修改查询条件' : '添加查询条件'"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form :model="conditionForm" label-width="100px">
        <el-form-item label="字段名称" required>
          <el-select v-model="conditionForm.fieldName" placeholder="请选择">
            <el-option 
              v-for="field in availableFields"
              :key="field.prop"
              :label="field.label"
              :value="field.label"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="逻辑运算" required>
          <el-select v-model="conditionForm.operator" placeholder="请选择">
            <el-option label="等于" value="=" />
            <el-option label="不等于" value="!=" />
            <el-option label="大于" value=">" />
            <el-option label="大于等于" value=">=" />
            <el-option label="小于" value="<" />
            <el-option label="小于等于" value="<=" />
            <el-option label="包含" value="like" />
            <el-option label="不包含" value="not like" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="输入值" required>
          <el-input v-model="conditionForm.value" placeholder="请输入" />
        </el-form-item>
        
        <el-form-item label="条件关系">
          <el-select v-model="conditionForm.relation" placeholder="请选择">
            <el-option label="AND" value="and" />
            <el-option label="OR" value="or" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="conditionFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitConditionForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ElTree } from 'element-plus'

// 当前视图状态
const currentView = ref('overview')  // 'overview' 或 'entityData'
const treeFilterText = ref('')
const categoryTreeRef = ref<InstanceType<typeof ElTree>>()

// 监听树过滤文本变化
watch(treeFilterText, (val) => {
  categoryTreeRef.value?.filter(val)
})

// 分类树数据
const categoryTree = ref([
  {
    id: '1',
    name: '数据中心',
    type: 'folder',
    children: [
      {
        id: '1-1',
        name: '学校概况数据集',
        type: 'folder',
        children: []
      },
      {
        id: '1-2',
        name: '学生管理数据集',
        type: 'folder',
        children: [
          {
            id: '1-2-1',
            name: '学生基本数据类',
            type: 'folder',
            children: [
              { id: '1-2-1-1', name: '学生基本数据子类表', type: 'table', count: 4045 },
              { id: '1-2-1-2', name: '住宿子类表', type: 'table', count: 107 },
              { id: '1-2-1-3', name: '户口状况子类表', type: 'table', count: 999 },
              { id: '1-2-1-4', name: '通用通讯数据子类表', type: 'table', count: 174 },
              { id: '1-2-1-5', name: '学生基本数据子类表', type: 'table', count: 149 }
            ]
          },
          { id: '1-2-2', name: '本专科生新生数据类', type: 'folder', children: [] },
          { id: '1-2-3', name: '研究生招生数据类', type: 'folder', children: [] },
          { id: '1-2-4', name: '研究生招生辅助数据类', type: 'folder', children: [] },
          { id: '1-2-5', name: '研究生非学历教育辅助数据类', type: 'folder', children: [] },
          { id: '1-2-6', name: '休学、防疫数据类', type: 'folder', children: [] },
          { id: '1-2-7', name: '学籍数据类', type: 'folder', children: [] },
          { id: '1-2-8', name: '学位、学历数据类', type: 'folder', children: [] },
          { id: '1-2-9', name: '实践活动数据类', type: 'folder', children: [] },
          { id: '1-2-10', name: '经济资助数据类', type: 'folder', children: [] },
          { id: '1-2-11', name: '社团（协会）辅助数据类', type: 'folder', children: [] },
          { id: '1-2-12', name: '毕业就业相关数据类', type: 'folder', children: [] },
          { id: '1-2-13', name: '就业辅助数据类', type: 'folder', children: [] }
        ]
      },
      {
        id: '1-3',
        name: '教学管理数据集',
        type: 'folder',
        children: []
      }
    ]
  }
])

// 总体统计数据
const totalStats = reactive({
  entities: 243,
  records: 12968,
  categories: 27,
  attributes: 523
})

// 总览表格数据
const overviewTableData = ref([
  { id: 1, entityCnName: '学生基本数据子类表', tableName: 'gxxs0101', recordCount: 4045, fieldCount: 20 },
  { id: 2, entityCnName: '学籍基本数据子类表', tableName: 'gxxs0701', recordCount: 3931, fieldCount: 21 },
  { id: 3, entityCnName: '社团（协会）辅助数据类表', tableName: 'gxxs11', recordCount: 999, fieldCount: 9 },
  { id: 4, entityCnName: '项目基本数据子类表', tableName: 'gxcw0301', recordCount: 174, fieldCount: 22 },
  { id: 5, entityCnName: '变学年数据子类表', tableName: 'gxxs1001', recordCount: 149, fieldCount: 10 },
  { id: 6, entityCnName: '住宿子类表', tableName: 'gxxs0110', recordCount: 107, fieldCount: 7 },
  { id: 7, entityCnName: '公文基础数据子类表', tableName: 'gxbg0101', recordCount: 99, fieldCount: 13 },
  { id: 8, entityCnName: '科技论文基本数据子类表', tableName: 'gxky0303', recordCount: 98, fieldCount: 23 },
  { id: 9, entityCnName: '获奖成果基本数据子类表', tableName: 'gxky0310', recordCount: 50, fieldCount: 18 },
  { id: 10, entityCnName: '鉴定成果子类表', tableName: 'gxky0306', recordCount: 39, fieldCount: 18 }
])

// 当前实体信息
const currentEntity = reactive({
  id: '',
  name: '',
  code: ''
})

// 实体字段列信息
const entityColumns = ref([])

// 实体数据列表
const entityDataList = ref([])

// 表格与分页
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(243)
const selectedRows = ref([])

// 高级查询相关
const advancedSearchVisible = ref(false)
const conditionFormVisible = ref(false)
const isEditingCondition = ref(false)
const currentEditIndex = ref(-1)
const searchConditions = ref([])

// 查询条件表单
const conditionForm = reactive({
  fieldName: '',
  operator: '=',
  value: '',
  relation: 'and'
})

// 可用字段
const availableFields = computed(() => {
  return [
    { prop: 'id', label: 'ID' },
    { prop: 'gender', label: '性别码' },
    { prop: 'name', label: '姓名' },
    { prop: 'birthday', label: '出生日期' },
    { prop: 'province', label: '籍贯' },
    { prop: 'nameCode', label: '名称码' },
    { prop: 'countryCode', label: '国籍地区码' },
    { prop: 'idType', label: '身份证件类型码' },
    { prop: 'idNumber', label: '身份证件号' },
    { prop: 'marriageCode', label: '婚姻状况码' },
    { prop: 'nationalityCode', label: '民族码' }
  ]
})

// 初始化
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = () => {
  tableLoading.value = true
  setTimeout(() => {
    tableLoading.value = false
    // 初始化实体数据列
    if (currentView.value === 'entityData') {
      entityColumns.value = [
        { prop: 'id', label: 'ID', width: '120' },
        { prop: 'gender', label: '性别码', width: '80' },
        { prop: 'name', label: '姓名', width: '100' },
        { prop: 'birthday', label: '出生日期', minWidth: '120' },
        { prop: 'province', label: '籍贯', minWidth: '120' },
        { prop: 'nameCode', label: '名称码', width: '80' },
        { prop: 'countryCode', label: '国籍地区码', width: '100' },
        { prop: 'idType', label: '身份证件类型码', width: '120' },
        { prop: 'idNumber', label: '身份证件号', minWidth: '180' },
        { prop: 'marriageCode', label: '婚姻状况码', width: '100' },
        { prop: 'nationalityCode', label: '民族码', width: '80' }
      ]
      
      // 模拟实体数据
      entityDataList.value = [
        { id: '16253236', gender: '2', name: '陆哈哈', birthday: '2002-02-24 00:00:00', province: '山西省临汾市', nameCode: '01', countryCode: 'CHN', idType: '1', idNumber: '141103220202024729', marriageCode: '10', nationalityCode: '01' },
        { id: '30962749', gender: '2', name: '陆哈哈', birthday: '2002-02-24 00:00:00', province: '山西省临汾市', nameCode: '01', countryCode: 'CHN', idType: '1', idNumber: '141103220202024729', marriageCode: '10', nationalityCode: '01' },
        { id: '16253656', gender: '1', name: '李春治', birthday: '2004-01-26 00:00:00', province: '浙江省嘉兴市', nameCode: '01', countryCode: 'CHN', idType: '1', idNumber: '33048120040126924', marriageCode: '10', nationalityCode: '01' },
        { id: '67284037', gender: '1', name: '王鑫', birthday: '2004-08-15 00:00:00', province: '河南省驻马店', nameCode: '01', countryCode: 'CHN', idType: '1', idNumber: '411701200408157553', marriageCode: '10', nationalityCode: '01' },
        { id: '16253656', gender: '2', name: '张敖歌', birthday: '2003-06-09 00:00:00', province: '甘肃省兰州市', nameCode: '01', countryCode: 'CHN', idType: '1', idNumber: '6201052003060933', marriageCode: '10', nationalityCode: '01' },
        { id: '67284037', gender: '2', name: '程渝', birthday: '2003-08-06 00:00:00', province: '山西省长治市', nameCode: '01', countryCode: 'CHN', idType: '1', idNumber: '1404812003080634', marriageCode: '10', nationalityCode: '01' },
        { id: '16253656', gender: '2', name: '李玮', birthday: '2003-10-07 00:00:00', province: '辽宁省营口市', nameCode: '01', countryCode: 'CHN', idType: '1', idNumber: '21080120031007664', marriageCode: '10', nationalityCode: '01' }
      ]
    }
  }, 500)
}

// 刷新数据
const refreshData = () => {
  currentPage.value = 1
  loadData()
}

// 分页变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 树节点点击
const handleNodeClick = (data) => {
  if (data.type === 'table') {
    currentView.value = 'entityData'
    currentEntity.id = data.id
    currentEntity.name = data.name
    currentEntity.code = data.id.split('-').pop()
    loadData()
  } else if (data.type === 'folder') {
    // 如果是文件夹，则展开/折叠节点
  }
}

// 获取节点图标类
const getNodeIconClass = (data) => {
  if (data.type === 'folder') {
    return 'i-carbon-folder'
  } else if (data.type === 'table') {
    return 'i-carbon-data-table'
  }
  return 'i-carbon-document'
}

// 树节点过滤
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 表格多选变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 显示高级查询对话框
const showAdvancedSearch = () => {
  advancedSearchVisible.value = true
}

// 添加查询条件
const addSearchCondition = () => {
  isEditingCondition.value = false
  conditionForm.fieldName = ''
  conditionForm.operator = '='
  conditionForm.value = ''
  conditionForm.relation = 'and'
  conditionFormVisible.value = true
}

// 编辑查询条件
const editSearchCondition = (row, index) => {
  isEditingCondition.value = true
  currentEditIndex.value = index
  
  // 复制当前条件到表单
  conditionForm.fieldName = row.fieldName
  conditionForm.operator = row.operator
  conditionForm.value = row.value
  conditionForm.relation = row.relation || 'and'
  
  conditionFormVisible.value = true
}

// 删除查询条件
const removeSearchCondition = (index) => {
  ElMessageBox.confirm('确定要删除此查询条件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    searchConditions.value.splice(index, 1)
    ElMessage.success('删除查询条件成功')
  }).catch(() => {
    // 取消删除
  })
}

// 清除所有查询条件
const clearSearchConditions = () => {
  searchConditions.value = []
}

// 提交查询条件表单
const submitConditionForm = () => {
  // 验证表单
  if (!conditionForm.fieldName || !conditionForm.operator || !conditionForm.value) {
    ElMessage.error('请完整填写查询条件')
    return
  }
  
  // 创建新的条件对象
  const newCondition = {
    fieldName: conditionForm.fieldName,
    operator: conditionForm.operator,
    value: conditionForm.value,
    relation: conditionForm.relation
  }
  
  if (isEditingCondition.value && currentEditIndex.value !== -1) {
    // 更新现有条件
    searchConditions.value[currentEditIndex.value] = newCondition
  } else {
    // 添加新条件
    searchConditions.value.push(newCondition)
  }
  
  conditionFormVisible.value = false
  ElMessage.success(isEditingCondition.value ? '修改查询条件成功' : '添加查询条件成功')
}

// 执行高级查询
const executeAdvancedSearch = () => {
  if (searchConditions.value.length === 0) {
    ElMessage.warning('请添加至少一个查询条件')
    return
  }
  
  // 模拟执行查询
  tableLoading.value = true
  setTimeout(() => {
    tableLoading.value = false
    advancedSearchVisible.value = false
    ElMessage.success('高级查询执行成功')
    
    // 在实际应用中，这里会根据查询条件过滤或重新请求数据
  }, 800)
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(`此操作将永久删除这些文件，是否继续？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除操作
    tableLoading.value = true
    setTimeout(() => {
      tableLoading.value = false
      ElMessage.success('删除成功')
      loadData()
    }, 500)
  }).catch(() => {
    // 取消删除
  })
}
</script>

<style scoped lang="scss">
.masterdata-manage {
  height: calc(100vh - 120px);
  
  .tree-container {
    transition: all 0.3s;
    
    :deep(.el-tree-node__content) {
      height: 32px;
    }
    
    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: #f0f7ff;
      color: #409eff;
    }
  }
  
  .content-container {
    .stat-card {
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    }
  }
  
  :deep(.el-table) {
    --el-table-header-bg-color: #f5f7fa;
    
    .el-table__header th {
      font-weight: 600;
    }
  }
  
  .search-conditions {
    border-left: 4px solid #409eff;
  }
}
</style>
